<template>
  <div class="main">
    <div class="sidebar-menu-con" :class="{'main-hide-text': shrink}">
      <div class="sidebar-menu-con" :style="{width: shrink?'60px':'200px', overflow: shrink ? 'visible' : 'auto'}">
        <scroll-bar ref="scrollBar">
          <shrinkable-menu
            :shrink="shrink"
            @on-change="handleSubmenuChange"
            :theme="menuTheme"
            :before-push="beforePush"
            :open-names="openedSubmenuArr"
            :menu-list="menuList"
            :dynamicMenuRoutes="dynamicMenuRoutes"
          >
            <div slot="top" class="logo-con">
              <!--<img v-show="!shrink" src="../assets/logo.png" key="max-logo"/>-->
              <p v-show="!shrink" key="max-logo">HRCMS建站系统</p>
              <p v-show="shrink" key="min-logo">M</p>
            </div>
          </shrinkable-menu>
        </scroll-bar>
      </div>
    </div>
    <div class="main-header-con" :style="{paddingLeft: shrink?'60px':'200px'}">
      <div class="main-header">
        <div class="navicon-con">
          <Button :style="{transform: 'rotateZ(' + (this.shrink ? '-90' : '0') + 'deg)'}" type="text" @click="toggleClick">
            <Icon type="navicon" size="32"></Icon>
          </Button>
        </div>
        <div class="header-middle-con">
          <div class="main-breadcrumb">
            <breadcrumb-nav :currentPath="currentPath"></breadcrumb-nav>
          </div>
        </div>
        <div class="header-avator-con">
          <div class="user-dropdown-menu-con">
            <Row type="flex" justify="end" align="middle" class="user-dropdown-innercon">
              <Dropdown transfer trigger="click" @on-click="handleClickUserDropdown">
                <a href="javascript:void(0)">
                  <span class="main-user-name">{{ userName }}</span>
                  <Icon type="arrow-down-b"></Icon>
                </a>
                <DropdownMenu slot="list">
                  <DropdownItem name="ownSpace">修改密码</DropdownItem>
                  <password-update v-if="passwordShowVisiable"
                                   ref="passwordUpdate"></password-update>
                  <DropdownItem name="loginout" divided>退出登录</DropdownItem>
                </DropdownMenu>
              </Dropdown>
              <Avatar style="background-color: #87d068;margin-left: 10px;" icon="person" />
              <!--<Avatar :src="avatorPath" style="background: #619fe7;margin-left: 10px;"></Avatar>-->
            </Row>
          </div>
        </div>
      </div>
      <div class="tags-con">
        <tags-page-opened :pageTagsList="pageTagsList"></tags-page-opened>
      </div>
    </div>
    <div class="single-page-con" :style="{left: shrink?'60px':'200px'}">
      <div class="single-page">
        <iframe v-if="currentOpendPageObj && currentOpendPageObj.type === 'iframe'"
                :src="currentOpendPageObj.iframeUrl" width="100%" :style="{'height': documentClientHeight + 'px'}" frameborder="0" scrolling="yes"></iframe>
        <keep-alive v-else :include="cachePage">
          <router-view></router-view>
        </keep-alive>
      </div>
    </div>
  </div>
</template>

<script>
import shrinkableMenu from './main-components/shrinkable-menu/shrinkable-menu.vue';
import tagsPageOpened from './main-components/tags-page-opened.vue';
import breadcrumbNav from './main-components/breadcrumb-nav.vue';
import scrollBar from '@/components/scroll-bar/vue-scroller-bars';
import passwordUpdate from './own-space/password-update'
import util from '@/libs/util';
import Cookies from 'js-cookie';
export default {
  components: {
    shrinkableMenu,
    tagsPageOpened,
    breadcrumbNav,
    scrollBar,
    passwordUpdate
  },
  data () {
    return {
      shrink: false,
      passwordShowVisiable: false,
      iconSize: 30,
      openedSubmenuArr: this.$store.state.app.openedSubmenuArr,
      dynamicMenuRoutes: [],
      currentOpendPageObj: {
        type: 'module',
        iframeUrl: ''
      } // 当前路由封装对象
    }
  },
  computed: {
    menuList: {
      get () { return this.$store.state.app.menuList; }, // 菜单列表
      set (val) { this.$store.commit('updateMenuList', val) }
    },
    pageTagsList () {
      return this.$store.state.app.pageOpenedList; // 打开的页面对象
    },
    currentPath () {
      return this.$store.state.app.currentPath; // 当前面包屑数组
    },
    menuTheme () {
      return this.$store.state.app.menuTheme;
    },
    cachePage () {
      return this.$store.state.app.cachePage;
    },
    userId: {
      get () { return this.$store.state.user.id },
      set (val) { this.$store.commit('user/updateId', val) }
    },
    userName: {
      get () { return this.$store.state.user.name },
      set (val) { this.$store.commit('user/updateName', val) }
    },
    roleNames: {
      get () {
        return this.$store.state.user.roleNames
      },
      set (val) {
        this.$store.commit('user/updateRoleNames', val)
      }
    },
    lastLoginTime: {
      get () {
        return this.$store.state.user.lastLoginTime
      },
      set (val) {
        this.$store.commit('user/updateLastLoginTime', val)
      }
    },
    documentClientHeight: {
      get () { return this.$store.state.app.documentClientHeight },
      set (val) { this.$store.commit('updateDocumentClientHeight', val) }
    }
  },
  methods: {
    init () {
      let pathArr = util.setCurrentPath(this, this.$route);
      this.$store.commit('updateMenulist');
      if (pathArr.length >= 2) {
        this.$store.commit('addOpenSubmenu', pathArr[1].name);
      }
      this.checkTag(this.$route.name);
      // 是否要打开iframe
      if (this.$route.meta.menuId) {
        this.handleIframe(this.$route.meta.menuId);
      }
    },
    // 左侧导航栏收缩开关
    toggleClick () {
      this.shrink = !this.shrink;
    },
    // header 用户名下拉列表
    handleClickUserDropdown (name) {
      if (name === 'ownSpace') {
        this.passwordShowVisiable = true;
        this.$nextTick(() => {
          this.$refs.passwordUpdate.init();
        });
      } else if (name === 'loginout') {
        // 退出登陆
        // this.$store.commit('logout', this);
        this.$http({
          url: this.$http.adornUrl('/sys/logout'),
          method: 'post',
          data: this.$http.adornData()
        }).then(({data}) => {
          if (data && data.code === 0) {
            Cookies.remove('token');
            this.$router.replace({ name: 'login' });
            this.$router.options.isAddDynamicMenuRoutes = false;
            this.$store.commit('clearOpenedSubmenu');
            this.$store.commit('clearAllTags');
            // this.$store.commit('order/clearOrder');
            localStorage.clear();
            sessionStorage.clear();
          }
        });
      }
    },
    // 标签页是否打开
    checkTag (name) {
      // debugger
      let openPageHasTag = this.pageTagsList.some(item => {
        if (item.name === name) {
          return true;
        }
      });
      if (!openPageHasTag) {
        //  解决关闭当前标签后再点击回退按钮会退到当前页时没有标签的问题
        util.openNewPage(this, name, this.$route.params || {}, this.$route.query || {});
      }
    },
    handleSubmenuChange (val) {
      // console.log(val)
    },
    beforePush (name) {
      // if (name === 'accesstest_index') {
      //     return false;
      // } else {
      //     return true;
      // }
      return true;
    },
    scrollBarResize () {
      this.$refs.scrollBar.resize();
    },
    // 获取当前登陆人信息
    getUserInfo () {
      this.$http({
        url: this.$http.adornUrl('/sys/user/info'),
        method: 'get',
        params: this.$http.adornParams()
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.userId = data.user.userId || '';
          this.userName = data.user.username || '';
          this.roleNames = data.user.roleNameList ? data.user.roleNameList.join(',') : '无角色信息';
          this.lastLoginTime = data.user.lastLoginTime;
        }
      })
    },
    // 调整iframe高度 140：header高度
    resetClientHeight () {
      this.documentClientHeight = document.documentElement['clientHeight'] - 140;
      window.onresize = () => {
        this.documentClientHeight = document.documentElement['clientHeight'] - 140;
      }
    },
    // 设置iframe url
    handleIframe (menuId) {
      this.currentOpendPageObj = this.pageTagsList.filter((item) => {
        return item.menuId === menuId;
      })[0];
    }
  },
  watch: {
    '$route' (to) {
      this.$store.commit('setCurrentPageName', to.name);
      let pathArr = util.setCurrentPath(this, to);
      if (pathArr.length > 2) {
        this.$store.commit('addOpenSubmenu', pathArr[1].name);
      }
      this.checkTag(to.name);
      localStorage.currentPageName = to.name;
      // 是否要代开iframe
      this.handleIframe(to.meta.menuId);
    },
    openedSubmenuArr () {
      setTimeout(() => {
        this.scrollBarResize();
      }, 300);
    }
  },
  mounted () {
    this.init();
    window.addEventListener('resize', this.scrollBarResize);
    this.resetClientHeight();
  },
  created () {
    this.getUserInfo();
    this.menuList = JSON.parse(sessionStorage.getItem('menuList') || '[]');
    this.dynamicMenuRoutes = JSON.parse(sessionStorage.getItem('dynamicMenuRoutes') || '[]');
  },
  dispatch () {
    window.removeEventListener('resize', this.scrollBarResize);
  }
}
</script>

<style lang="less">
  @import "./main.less";
</style>
